package com.example.md.mddemo.exception;

import lombok.Data;

import java.util.HashMap;
import java.util.Map;

/**
 * Copyright © 2018年 ziniuxiaozhu. All rights reserved.
 *
 * @Author 临江仙 hzqiuxm@163.com
 *  Rest 风格请求的返回类型
 * @Date 2018/9/14 13:10
 */
@Data
public class RestResVo<T> {

    public static final int ERROR = -1;
    public static final int FAIL = 0;
    public static final int SUCCESS = 1;
    private int status;
    private String message;
    private String timestamp = String.valueOf(System.currentTimeMillis());
    private T data;

    /**
     * 成功
     * @param t
     * @param <T>
     * @return
     */
    public static  <T> RestResVo<T> success(T t){
        RestResVo<T> response = new RestResVo<>();
        response.setStatus(SUCCESS);
        response.setMessage("SUCCESS");
        response.setData(t);
        return response;
    }

    /**
     * 异常
     * @param e
     * @param <T>
     * @return
     */
    public static  <T> RestResVo<T> error(BusinessException e){
        RestResVo<T> response = new RestResVo<>();
        response.setStatus(e.getCode());
        response.setMessage(e.getMsg());
        response.setData(null);
        return response;
    }

    /**
     * 异常
     * @param e
     * @param <T>
     * @return
     */
    public static <T> RestResVo<T> error(Throwable e){
        RestResVo<T> response = new RestResVo<>();
        response.setStatus(ERROR);
        response.setMessage(e.toString());
        response.setData(null);
        return response;
    }

    /**
     * 失败
     * @param msg
     * @param <T>
     * @return
     */
    public static  <T> RestResVo<T> fail(String msg){
        RestResVo<T> response = new RestResVo<>();
        response.setStatus(FAIL);
        response.setMessage(msg);
        return response;
    }

    public  Map<String,Object> toMapData(){

        Map<String,Object> toMap = new HashMap<>();

        toMap.put("status",ERROR);
        toMap.put("message",this.message);

        return toMap;
    }
}
